import unittest
from alg import Solution
from gen import generate_test_cases

class TestNQueens(unittest.TestCase):
    def test_example(self):
        sol = Solution()
        n = 4
        result = sol.solveNQueens(n)
        # 打印 n=4 时的实际结果
        print(f"n={n} 时的解：{result}")

        # 验证输出格式
        self.assertIsInstance(result, list)
        if result:
            self.assertIsInstance(result[0], list)
            self.assertIsInstance(result[0][0], str)

        # 验证已知解
        expected = [
            [".Q..", "...Q", "Q...", "..Q."],
            ["..Q.", "Q...", "...Q", ".Q.."]
        ]
        self.assertEqual(len(result), 2)
        self.assertCountEqual([tuple(sol) for sol in result],
                              [tuple(sol) for sol in expected])

    def test_generated_cases(self):
        sol = Solution()
        test_cases = generate_test_cases(3)
        for n in test_cases:
            print(f"开始测试 n={n} 的情况")
            solutions = sol.solveNQueens(n)
            # 打印当前 n 对应的解
            print(f"n={n} 时的解：{solutions}")
            for soln in solutions:
                self._validate_solution(soln)

    def _validate_solution(self, solution):
        n = len(solution)
        queens = []

        # 收集皇后位置
        for row_idx, row in enumerate(solution):
            col_idx = row.index('Q')
            queens.append((row_idx, col_idx))

        # 检查冲突
        for i in range(len(queens)):
            for j in range(i + 1, len(queens)):
                r1, c1 = queens[i]
                r2, c2 = queens[j]

                self.assertNotEqual(c1, c2, "列冲突")
                self.assertNotEqual(abs(r1 - r2), abs(c1 - c2), "对角线冲突")

if __name__ == '__main__':
    unittest.main(verbosity=2)